(function() {
    'use strict';

    /**
     * @ngdoc directive
     * @name webApp.directive:myarea
     * @description

     用法：
     <cat-tree ng-model="item.cid" dft="1"></cat-tree>
     注：必须绑定ng-model;dft=1代表自动选中最后一个节点

     * # myarea
     */
    angular.module('webApp')
        //调用其他方法
        // .run(["$templateCache", "dataService", function($templateCache, dataService) {
        //     var tplName = "../assets/area.min.js";
        //     dataService.tpl(tplName).then(function(js) {
        //         $templateCache.put(tplName, js);
        //     });
        // }])
        .directive('myarea', function() {
            return {
                restrict: 'E',
                // template: '<ul id="catTreearea" class="ztree" >22</ul>',
                template: '<span> <i class="sui-icon icon-tb-cascades"></i> <a href="javascript:;"></a></span>',
                // replace: true,
                require: 'ngModel',
                scope: {
                    ngModel: '=',
                    backcall: '&',
                },
                controller: ['$templateCache', '$scope', 'dataService', '$compile', '$timeout', function($templateCache, $scope, dataService, $compile, $timeout) {
                    var zTreeObj;
                    $scope.chosedId = null;

                    // $scope.addss = $templateCache.get("../assets/area.min.js");
                    $scope.areas = {};
                    // dataService.areaGet(page_size:3300).then(function(){

                    // })
                    dataService.areaGet({ query: { parent_id: 0 }, page_size: 34 }).then(function(provinces) {
                        async.map(provinces.areas, function(province, call) {
                            $scope.areas[province.area_id] = province;
                            call(null, null);
                        }, function(e, r) {
                            initData();
                        });
                    });
                    // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
                    var setting = {
                        check: {
                            enable: true,
                            chkStyle: "radio",
                            radioType: "all"
                        },
                        callback: {
                            onClick: function(event, treeId, treeNode, clickFlag) {

                                zTreeObj.checkNode(treeNode, true, true, true);
                            },
                            onCheck: function(event, treeId, treeNode) {
                                var znode = treeNode.getParentNode(); //父级
                                if (znode) {
                                    var fnodes = znode.getParentNode();
                                    if (fnodes) {
                                        var areastate = { name: fnodes.name + znode.name, id: fnodes.id + "," + znode.id };
                                        var areastatearys = { province: fnodes.name, city: znode.name };
                                    } else {
                                        var areastate = { name: znode.name };
                                    }
                                } else {
                                    var areastate = "";
                                }
                                $scope.fjvalue = areastate;
                                $scope.chosedCellNode = treeNode;
                                $scope.areastatearys = areastatearys;
                                $timeout(function() {
                                    $scope.checkedv = $scope.fjvalue.name + $scope.chosedCellNode.name;
                                });

                            },
                            onExpand: function(event, treeId, treeNode) {
                                $scope.areaGetQuery(treeNode.id).then(function(r) {
                                    var node = zTreeObj.getNodesByParam("id", treeNode.id * 10, treeNode);
                                    zTreeObj.removeNode(node[0], false);
                                    $scope.areaGetQuery(r.areas[0].area_id).then(function(is_r) {

                                        _.map(r.areas, function(area) {
                                            if (is_r.areas.length > 0) {
                                                var newTreeNode = zTreeObj.addNodes(treeNode, { id: area.area_id, pId: area.parent_id, name: area.area, nocheck: true, checked: false, open: false });
                                                zTreeObj.addNodes(newTreeNode[0], { id: area.area_id * 10, pId: area.area_id, name: area.area, nocheck: true, checked: false, open: false }, true);
                                            } else {
                                                zTreeObj.addNodes(treeNode, { id: area.area_id, pId: area.parent_id, name: area.area, checked: false, open: true });
                                            }
                                        });
                                    });
                                })
                            }
                        },
                        data: {
                            simpleData: {
                                enable: true
                            }
                        }
                    };
                    $scope.areaGetQuery = function(area_id) {
                        var qeurys = { query: { parent_id: area_id }, page_size: 100 };
                        return dataService.areaGet(qeurys).then(function(r) {
                            return r
                        })
                    }
                    $scope.showPop = function() {
                        //<input type="text" ng-model="dass" style="width:200px;">
                        $timeout(function() {

                            $.alert({
                                backdrop: 'static',
                                keyboard: true,
                                title: '{{"choice" | translate}}',
                                body: '<div><div style="height:365px;overflow-y: scroll;"><ul id="catTreearea" class="ztree" ></ul></div><div ng-show="fjvalue.name" style="margin-top: 10px;">{{"area" | translate}}：{{checkedv}}</div></div>',
                                okBtn: '{{"ok" | translate}}',
                                closeBtn: true,
                                transition: true,
                                // width: 'small',
                                height: "400px",
                                show: function(e) {
                                    zTreeObj = $.fn.zTree.init($("#catTreearea"), setting, $scope.zNodes);
                                    $compile($(e.currentTarget).contents())($scope);
                                    return true;
                                },
                                okHide: function(e) {
                                    $timeout(function() {
                                        if ($scope.fjvalue && $scope.chosedCellNode) {
                                            $scope.dass = $scope.dass || '';
                                            $scope.ngModel = { region_name: $scope.fjvalue.name + $scope.chosedCellNode.name, id: $scope.fjvalue.id + ',' + $scope.chosedCellNode.id,province:$scope.areastatearys.province,city:$scope.areastatearys.city,district:$scope.chosedCellNode.name };
                                            console.error(" $scope.ngModel", $scope.ngModel);
                                            if ($scope.backcall) {
                                                $scope.backcall({ data: $scope.ngModel });
                                            }
                                        }

                                    });
                                },
                            });
                        })

                    }

                    // zTree 的数据属性，深入使用请参考 API 文档（zTreeNode 节点数据详解）
                    function initData() {
                        $scope.zNodes = [];

                        $timeout(function() {
                            for (var i in $scope.areas) {
                                if ($scope.areas[i].type == 3) {
                                    $scope.zNodes.push({ id: $scope.areas[i].area_id, pId: $scope.areas[i].parent_id, name: $scope.areas[i].area, checked: false, open: true });
                                } else {
                                    $scope.zNodes.push({ id: $scope.areas[i].area_id, pId: $scope.areas[i].parent_id, name: $scope.areas[i].area, nocheck: true, checked: false, open: false });
                                    $scope.zNodes.push({ id: $scope.areas[i].area_id * 10, pId: $scope.areas[i].area_id, name: $scope.areas[i].area, nocheck: true, checked: false, open: false });

                                }
                            }
                        }, 500)

                    }
                    // initData();
                }],
                link: function(scope, element, attrs, ctrl) {
                    //处理数据，得到想要 的数据
                    //绑定点击事件
                    element.bind("click", function() {
                        scope.showPop();
                    });
                    element.addClass("address");
                }
            }
        });
})();